package cn.javass.xgen.util.readxml;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 上下文，存放解释执行时的全局信息
 */
public class Context {

    private static Document document = null;
    /**
     * 上一次被处理的多个父节点的元素
     */
    private List<Element> preEles = new ArrayList<Element>();

    /**
     * 缓存多个context实例
     */
    private static Map<String, Context> mapCtx = new HashMap<String, Context>();

    private Context(Document document) {
        this.document = document;
    }

    public static Context getInstance(String filePathName) throws Exception {
        Context c = mapCtx.get(filePathName);
        if (c == null) {
            document = XmlUtil.getDocument(filePathName);
            c = new Context(document);
            mapCtx.put(filePathName, c);
        }
        //先初始化一下，把父节点内容清空
        c.init();
        return c;
    }

    private void init() {
        preEles = new ArrayList<Element>();
    }

    public Document getDocument() {
        return document;
    }

    public List<Element> getPreEles() {
        return preEles;
    }

    public void setPreEles(List<Element> preEles) {
        this.preEles = preEles;
    }

    /**
     * 根据父元素和当前元素名称取出当前元素名称对应的元素
     *
     * @param pEle
     * @param eleName
     * @return
     */
    public List<Element> getNowEles(Element pEle, String eleName) {
        List<Element> nowEles = new ArrayList<Element>();
        NodeList childNodes = pEle.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            if (childNodes.item(i) instanceof Element) {
                Element ele = (Element) childNodes.item(i);
                if (ele.getTagName().equals(eleName)) {
                    nowEles.add(ele);
                }
            }
        }
        return nowEles;

    }

    /**
     * 实现支持判断元素额属性等于某个条件值的情况
     * @param ele
     * @param condition
     * @return
     */
    public boolean judgeCondition(Element ele, String condition) {
        if (null == condition || condition.trim().length() == 0) {
            return true;
        }
        String[] ss = condition.split("=");
        if (ss[1] != null && ss[1].equals(ele.getAttribute(ss[0]))) {
            return true;
        }
        return false;
    }






}
